package api

import (
	"ginfast/app/mall/dto"
	"ginfast/app/mall/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/pkg/tree"
	"ginfast/util"
)

// Category 分类
type Category struct {
}

// ListHandler 列表
func (Category) ListHandler(c *ginx.Context) {
	var data []model.Category
	err := orm.DbFind(&data)
	c.JSONWriteData(data, err)
}

// PageHandler 列表
func (Category) PageHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	var data []model.Category
	total, _ := p.DbModelWhere(&model.Category{}).Find(&data)
	c.JSONWriteTotal(total, data)
}

// TreeHandler 列表
func (Category) TreeHandler(c *ginx.Context) {
	var trees []tree.Node
	orm.DB().Model(model.Category{}).Scan(&trees)
	data := tree.Build(trees)
	c.JSONWriteData(data)
}

// ListHandler 列表
func (Category) ListParentHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	id := c.Param("id")
	var data []model.Category
	total, _ := p.DbModelWhere(&model.Category{}, func(dw *orm.DbWhere) {
		dw.EqualNumber("ParentID", id)
	}).Find(&data)
	c.JSONWriteTotal(total, data)
}

// GetHandler 查询
func (Category) GetHandler(c *ginx.Context) {
	util.QueryByID(&model.Category{}, c)
}

// AddHandler 新增
func (Category) AddHandler(c *ginx.Context) {
	var p model.Category
	//获取参数
	err := c.MustBind(&p.CategoryOpt)
	if err != nil {
		return
	}
	err = orm.DbCreate(&p)
	c.JSONWriteError(err)
}

// UpdateHandler 修改
func (Category) UpdateHandler(c *ginx.Context) {
	var p model.Category
	//获取参数
	err := c.MustBind(&p.CategoryOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	c.JSONWriteError(err)
}

// DeleteHandler 删除
func (Category) DeleteHandler(c *ginx.Context) {
	util.Deletes(&model.Category{}, c)
}

func (o Category) Routers(r *ginx.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/list/:id", o.ListParentHandler)
	r.GET("/tree", o.TreeHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.PUT("", o.UpdateHandler)
	r.POST("", o.AddHandler)
	r.DELETE("", o.DeleteHandler)
}
